package nio;

import java.util.HashMap;
import java.util.Iterator;

import entity.Job;
import entity.Node;
import entity.Task;

public class Service {
	public static String KKK_0= "|";
	public static String KKK_1= "\r\n";
	public static String KKK_2= "#";
	//00
	public static String nodeList(){
		String rs = "";
		Iterator<Integer> nodeI = NioRoot.nodeMap.keySet().iterator();
		Node node = null;
		while(nodeI.hasNext()){
			node = NioRoot.nodeMap.get(nodeI.next());
			if(node.getJob() != null){
				rs = rs + node.getId() + "|" + node.getName() + "|" + node.getStatus() + "|" + node.getPort() +"|"  + node.getJob().getTask().getId() +"|"  + node.getJob().getId() +"|"+ node.getJob().getStatus() +"|" + KKK_1;
			}else{
				rs = rs + node.getId() + "|" + node.getName() + "|" + node.getStatus() + "|" + node.getPort() +"|" + KKK_1;
			}
		}
		return rs;
	}
	
	//11
	public static String taskList(){
		String rs = "";
		Iterator<Integer> nodeI = NioRoot.taskMap.keySet().iterator();
		Task task = null;
		while(nodeI.hasNext()){
			task = NioRoot.taskMap.get(nodeI.next());
			rs = rs + task.getId() + "|" + task.getName() + "|" + task.getStatus() + "|"  + KKK_1;
		}
		return rs;
	}
	
	//12|1
	private static String taskInfo(int parseInt) {
		String rs = "";
		Task task =  NioRoot.taskMap.get(parseInt);
		rs = rs + task.getId() + "|" + task.getName() + "|" + task.getStatus() + "|"  + KKK_1;
		Iterator<Integer> nodeI = task.getJobs().keySet().iterator();
		Job job = null;
		while(nodeI.hasNext()){
			job = task.getJobs().get(nodeI.next());
			rs = rs + job.getId() + "|" + job.getName() + "|" + job.getStatus() + "|"  + KKK_1;
		}
		return rs;
	}
	
	//10|20
	public static String subTask(int frames){
		String rs = "OK";
		Task task = new Task();
		task.setId(NioRoot.taskMap.size()+1);
		task.setStatus(0);
		task.setName("task" + task.getId());
		task.setJobs(new HashMap<Integer, Job>());
		Job job = null;
		for(int i = 0; i < frames;i++){
			job = new Job();
			job.setId(i);
			job.setStatus(0);
			job.setName("frame" + job.getId());
			job.setTask(task);
			task.getJobs().put(i, job);
		}
		NioRoot.taskMap.put(task.getId(), task);
		return rs;
	}
	
	
	public static String execute(String command){
		String[] commands = command.split("\\|"); 
		String rs = "";
		switch (Integer.parseInt(commands[0])) {
		case 00:
			rs = nodeList();
			break;
		case 10:
			rs = subTask(Integer.parseInt(commands[1]));
			Controller.notice();
			break;	
		case 11:
			rs = taskList();
			break;
		case 12:
			rs = taskInfo(Integer.parseInt(commands[1]));
			break;	
		default:
			break;
		}
		
		return rs;
	}

	
}
